<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片内容 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表内容 -->
      <el-table :data="rolesInfo" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div>
              <el-row
                :class="['borderBottom', index == 0 ? 'borderTop' : '']"
                :gutter="20"
                v-for="(r1, index) in scope.row.children"
                :key="r1.id"
              >
                <!-- 第一列放一级 -->
                <el-col :span="5">
                  <el-tag closable @close="closeTag(scope.row, r1.id)">{{
                    r1.authName
                  }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <!-- 第二列放二和三级级 -->
                  <el-row
                    :class="[index == 0 ? '' : 'borderTop']"
                    :gutter="20"
                    v-for="(r2, index) in r1.children"
                    :key="r2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        closable
                        @close="closeTag(scope.row, r2.id)"
                        type="success"
                        >{{ r2.authName }}</el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级 -->
                    <el-col :span="18">
                      <el-tag
                        closable
                        @close="closeTag(scope.row, r3.id)"
                        type="warning"
                        v-for="(r3, index) in r2.children"
                        :key="r3.id"
                        >{{ r3.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <div>
              <el-button
                @click="editRole(scope.row)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                >编辑</el-button
              >
              <el-button
                @click="deleteRole(scope.row.id)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                >删除</el-button
              >
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRights(scope.row)"
                >分配权限</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色弹出会话框 -->
    <el-dialog
      title="添加角色"
      @close="addClose"
      :visible.sync="addRoleDialog"
      width="50%"
    >
      <!-- 会话框内容 -->
      <el-form
        ref="addRoleRef"
        :rules="addRoleRules"
        :model="addRoleForm"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 会话框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="sureAndReq">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色会话窗口 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialog"
      width="50%"
      @close="editClose"
    >
      <!-- 内容 -->
      <el-form
        :model="RoleInfoByid"
        :rules="editRoleRoles"
        ref="editRoleRef"
        label-width="100px"
      >
        <el-form-item label="角色ID" prop="roleId">
          <el-input v-model="RoleInfoByid.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="RoleInfoByid.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="RoleInfoByid.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="sureAndReqEdit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限会话框 -->
    <el-dialog
  title="分配权限"
  :visible.sync="setRightsDialog"
  width="50%"
  @close="closeRightDialog">
  <!-- 树形列表 -->  
  <el-tree ref="treeRef" default-expand-all :default-checked-keys="arrayKeyTree" show-checkbox node-key="id" :data="treeRolesInfo" :props="rightsTree"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightsDialog = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      // 所有角色信息
      rolesInfo: [],
      // 添加角色会话框是否可见
      addRoleDialog: false,
      // 添加角色会话框表单数据
      addRoleForm: {
        roleName: "",
        roleDesc: "",
      },
      // 添加角色会话框表单校验
      addRoleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      // 编辑会话框是否可见
      editRoleDialog: false,

      editRoleRoles: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      RoleInfoByid: {
        roleId: "",
        roleName: "",
        roleDesc: "",
      },

      // 分配权限会话框是否显示
      setRightsDialog:false,

      // 角色权限树形列表
      treeRolesInfo:[],

      // 树形列表显示的数据
      rightsTree:{
        children:'children',
        label:'authName'
      },
      
      // 树形默认选中数组
      arrayKeyTree:[],

      // 保存id给分配权限会话框使用
      rowInfo:{
        id:''
      },
    };
  },
  methods: {
    // 获取角色信息
    async getRolesInfo() {
      let { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色信息失败");
      } else {
        this.rolesInfo = res.data;
      }
    },

    // 添加新角色按钮
    addRole() {
      this.addRoleDialog = true;
    },

    // 添加角色请求
    async reqRole() {
      let { data: res } = await this.$http.post("roles", this.addRoleForm);
      if (res.meta.status !== 201) {
        return this.$message.error("添加角色失败");
      } else {
        this.$message.success("成功添加角色");
      }
    },

    // 会话框点击确定验证表单+发送请求
    sureAndReq() {
      this.$refs.addRoleRef.validate(async (valid) => {
        if (valid) {
          await this.reqRole();
          this.addRoleDialog = false;
          this.getRolesInfo();
        }
      });
    },

    // 关闭会话框事件
    addClose() {
      this.$refs.addRoleRef.resetFields();
    },
    editClose() {
      this.$refs.editRoleRef.resetFields();
    },

    // 编辑角色按钮
    async editRole(row) {
      this.editRoleDialog = true;
      const { data: res } = await this.$http.get(`roles/${row.id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("id获取用户信息失败");
      } else {
        this.RoleInfoByid = res.data;
      }
    },

    // 编辑会话框点击确定+发送数据
    async sureAndReqEdit() {
      const { data: res } = await this.$http.put(
        `roles/${this.RoleInfoByid.roleId}`,
        {
          roleName: this.RoleInfoByid.roleName,
          roleDesc: this.RoleInfoByid.roleDesc,
        }
      );
      if (res.meta.status !== 200) {
        this.$message.error("编辑角色失败");
        return (this.editRoleDialog = false);
      } else {
        this.getRolesInfo();
        this.$message.success("编辑角色成功");
        return (this.editRoleDialog = false);
      }
    },

    // 删除角色
    deleteRole(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);
          this.getRolesInfo();
          if (res.meta.status !== 200) {
            return Promise.reject(new Error("faile"));
          } else {
            this.getRolesInfo();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "删除角色失败",
          });
        });
    },

    // 删除标签
    async closeTag(row, rightId) {
      if (confirm("是否要移除此权限？")) {
        let { data: res } = await this.$http.delete(
          `roles/${row.id}/rights/${rightId}`
        );
        if (res.meta.status !== 200) {
          return this.$message.error("删除失败");
        } else {
          row.children = res.data;
          this.$message.success("删除成功");
        }
      }
    },

    // 分配权限按钮
    async setRights(row){
      this.rowInfo.id = row.id
      // 调用递归函数，获取三级节点id
      this.getLeafKeys(row,this.arrayKeyTree)
      // 打开会话框
      this.setRightsDialog = true
      const {data:res} = await this.$http.get('rights/tree')
      if(res.meta.status !== 200) return this.$message.error('获取数据失败')
      else{
        this.treeRolesInfo = res.data
        }
    },
    // 关闭分配权限会话框的回调函数
    closeRightDialog(){
      this.arrayKeyTree = []
    },

    // 通过递归的形式，获取角色下所有三级权限的id，并保存到arrayKeyTree数组中
    getLeafKeys(node,arr){
      // 如果当前node节点不包含children属性，则是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafKeys(item,arr)
      )
    },

    // 为角色分配权限
    async allotRights(){
      let keys = [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
      let idStr = keys.join(',')
      const {data:res} = await this.$http.post(`roles/${this.rowInfo.id}/rights`,{rids:idStr})
      if(res.meta.status !== 200){
        this.setRightsDialog = false
        return this.$message.error('分配权限失败')
      }else{
        this.setRightsDialog = false
        this.getRolesInfo()
        return this.$message.success('分配权限成功')
      }
    }

  },
  mounted() {
    this.getRolesInfo();
  },
};
</script>

<style lang="less" scoped>
.borderTop {
  border-top: 1px solid #eeeeee;
}
.borderBottom {
  border-bottom: 1px solid #eeeeee;
}
.el-tag {
  margin: 7px;
}
.el-button {
  margin-bottom: 5px;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>